/*
 * RequestDispatcher.java July 2009
 *
 * Copyright (C) 2009, Quirino Zagarese <quirino@laszloitalia.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
package org.eu4ria.core;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eu4ria.ActionResult;
import org.eu4ria.AppAction;
import org.eu4ria.AppModule;
import org.eu4ria.Application;
import org.eu4ria.core.hotdeploy.AppsListener;
import org.eu4ria.core.hotdeploy.DirectoryWatcher;
import org.eu4ria.serialization.Serializer;
import org.eu4ria.serialization.SerializerFactory;

public class RequestDispatcher extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) {
		ServletContext context = config.getServletContext();
		System.out.print("Starting deployment...");
		String path = context.getRealPath(context.getContextPath());
		path = path.substring(0, path.lastIndexOf(File.separator + "EU4RIA"));
		path = path.replaceAll("(/\\./)+", File.separator);
		ArchiveDeployer deployer = ArchiveDeployer.getInstance();
		deployer.setAppsScanPath(path + File.separator +"WEB-INF" + File.separator +"deploy");
		deployer.deployApps();

		System.out.println("complete");
		DirectoryWatcher dw = new DirectoryWatcher(deployer.getAppsScanPath(),
				5);
		dw.addListener(new AppsListener());
		dw.start();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		executeAppAction(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		doGet(request, response);
	}

	private void executeAppAction(HttpServletRequest request,
			HttpServletResponse response) {
		Application application = AppRepository.getInstance()
				.getApplicationByHash(request.getParameter("appid"));
		AppModule module = application.getModulesByHash(request
				.getParameter("modid"));
		AppAction action = module
				.getActionByHash(request.getParameter("actionid"));
		ActionResult result = action.execute(request.getParameterMap());
		serialize(result, request, response);
	}

	private void serialize(ActionResult result, HttpServletRequest request,
			HttpServletResponse response) {

		SerializerFactory factory = SerializerFactory.getInstance();
		Serializer serializer = factory.getSerializer(result.getType());
		String output = "";
		response.setContentType("text/xml");
		if (result.getErrorMessage() != null) {
			output = "<response time=\"" + System.currentTimeMillis() + "\" >"
					+ "<exception message=\"" + result.getErrorMessage() + "\""
					+ " param=\"" + result.getParamErrorNum() + "\">"
					+ "<![CDATA[" + result.getStackTraceString() + "]]>"
					+ "</exception>" + "</response>";
		} else if (serializer != null) {
			output = "<response time=\"" + System.currentTimeMillis() + "\" >"
					+ serializer.serialize(result.getValue()) + "</response>";
		}
		System.out.println(output);
		try {
			response.getWriter().println(output);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
